// 自动更新
let lastSrcs = null;
const scriptReg = /<script[^>]*src=["'](?<src>[^"']+)["']/gim;

async function extractNewScripts() {
  try {
    const response = await fetch('/?_timestamp=' + Date.now());
    if (!response.ok) {
      console.warn('Fetch HTML failed with status:', response.status);
      return lastSrcs || [];
    }
    const html = await response.text();
    scriptReg.lastIndex = 0;
    const result = [];
    let match;
    while ((match = scriptReg.exec(html))) {
      result.push(match.groups.src);
    }
    return result;
  } catch (err) {
    console.error('Failed to fetch or parse scripts:', err);
    return lastSrcs || [];
  }
}

async function needUpdate() {
  const newScripts = await extractNewScripts();
  if (!lastSrcs) {
    lastSrcs = newScripts;
    return false;
  }

  if (lastSrcs.length !== newScripts.length) {
    lastSrcs = newScripts;
    return true;
  }

  for (let i = 0; i < lastSrcs.length; i++) {
    if (lastSrcs[i] !== newScripts[i]) {
      lastSrcs = newScripts;
      return true;
    }
  }

  return false;
}

const DURATION = 2000;

function autoRefresh() {
  setTimeout(async () => {
    try {
      const willUpdate = await needUpdate();
      if (willUpdate) {
        const result = confirm('检测到新的脚本，是否刷新页面？');
        if (result) {
          location.reload();
        }
      }
    } catch (err) {
      console.error('Auto-refresh check error:', err);
    }
    autoRefresh(); // 继续下一次轮询
  }, DURATION);
}

// 启动
autoRefresh();